package com.mf.utils;

import com.mf.entity.vo.UserVo;
import com.mf.exceptions.GraceException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @Author: lmf
 * @Create: 2024/7/9 16:31
 * Description:
 */
@Slf4j
public class JWTUtil {
    /**
     * token 过期时间 7天
     */
    private static  final long EXPIRE_TIME = 1000 * 60 * 60 * 24 * 7 ;
    /**
     * 密钥
     */
    private static final String SECRET = "rsk.098123.login";
    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "rsk.class.login";
    /**
     * subject
     */
    private static final String SUBJECT = "rsk.class.user.login";

    /**
     * 根据用户信息生成token
     */
    public static String createToken(UserVo userVo) {
        if(userVo == null){
            GraceException.display("用户信息为空");
        }

        String token = Jwts.builder()
                .setSubject(SUBJECT)
                .claim("userId", userVo.getId())
                .claim("name", userVo.getName())
                .claim("userName", userVo.getUserName())
                .claim("systemCode",userVo.getSystemCode())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();

        return TOKEN_PREFIX + token;
    }

    /**
     * 解密token
     */
    public static UserVo checkJwt(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            UserVo userVo = new UserVo();
            if (claims != null) {
                userVo.setId(claims.get("userId", Long.class));
                userVo.setName(claims.get("name", String.class));
                userVo.setUserName(claims.get("userName", String.class));
                userVo.setSystemCode(claims.get("systemCode",String.class));
                return userVo;
            }
            return null;
        } catch (Exception e) {
            log.error("token解析失败");
            return null;
        }
    }

}
